const escapeRegex = (string) => {
  return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}

export default function replacer(includes, searchValue, replaceValue) {
  return {
    name: 'vite-plugin-replace',

    transform: (code, id) => {
      const tests = includes.map(item => {
        if (typeof item === 'string') {
          return new RegExp(`${escapeRegex(item)}(?:$|\\?)`);
        }
        else {
          return item;
        }
      });

      if (tests.find(item => item.test(id))) {
        return {
          code: typeof replaceValue === 'string' ? code.replace(searchValue, replaceValue) : code.replace(searchValue, replaceValue),
          map: null,
        };
      }
    },
  }
}
